package com.mgq.netty.simpleNettyServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServer {
    public static void main(String[] args) {
        //进一步细分,有可能Handler执行的时间长,导致影响其他客户端的读写.可以创建一个独立的EventLoopGroup,去专门处理这种事件
        //通过addLast()将group和Handler进行绑定
        EventLoopGroup group = new DefaultEventLoop();
        log.debug("服务开始启动");
        new ServerBootstrap()
                //细分, 使用2个EventLoopGroup,第一个相当于boss,处理accept事件,第二个相当于worker,处理读写事件
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast("handler-1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                //ByteBuf buf = (ByteBuf) msg;
                                log.debug("--------------------");
                                //将消息传递给下一个Handler
                                ctx.fireChannelRead(msg);
                            }
                        });
                        ch.pipeline().addLast(group, "handler-2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                //ByteBuf buf = (ByteBuf) msg;
                                log.debug(msg.toString());
                                //log.debug(buf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                })
                .bind(8088);
    }
}

//细分后,消息经过了不同的handler进行了处理,第一个消息经过nioEventLoopGroup,第二个消息经过defaultEventLoop处理
//也就是说我们可以选择不同的group来处理消息,进一步进行细分. 如果某个handler处理任务时间长,我们就可以单独选择一个group来处理

//2021-12-04 17:21:11.269 [nioEventLoopGroup-4-1] DEBUG com.mgq.netty.c5.NettyServer - 1
//2021-12-04 17:21:11.271 [defaultEventLoop-1-1] DEBUG com.mgq.netty.c5.NettyServer - 1
//2021-12-04 17:21:57.437 [nioEventLoopGroup-4-2] DEBUG com.mgq.netty.c5.NettyServer - 2
//2021-12-04 17:21:57.437 [defaultEventLoop-1-1] DEBUG com.mgq.netty.c5.NettyServer - 2
//2021-12-04 17:22:23.880 [nioEventLoopGroup-4-1] DEBUG com.mgq.netty.c5.NettyServer - 3
//2021-12-04 17:22:23.880 [defaultEventLoop-1-1] DEBUG com.mgq.netty.c5.NettyServer - 3
